<template>
  <continer :isNoTabs="true" class="agentMonitoring">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="handleSearchFunc"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button size="mini" @click="reset">重置</el-button>
      <el-button type="primary" size="mini" @click="handleSearchFunc"
        >查询</el-button
      >
      <el-button
        type="primary"
        size="mini"
        @click="edit({}, 'add')"
        v-functions="['customer_config_field_insert']"
        >新增</el-button
      >
    </template>
    <template slot="content">
      <!-- 表格 -->
      <configTable
        ref="table"
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
        :headersConfig="false"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="item.show && !['oprate', 'enabled'].includes(item.prop)"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :sortable="item.sortable"
              :min-width="item.width || 80"
            >
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'enabled'"
              :key="index"
              :label="item.label"
              :width="80"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.enabled"
                  ><i class="V7_iconfont V7_iconV7tubiao_dian enable-span"></i
                  >启用</span
                >
                <span v-else
                  ><i class="V7_iconfont V7_iconV7tubiao_dian disable-span"></i
                  >停用</span
                >
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'oprate'"
              :key="index"
              :label="item.label"
              :resizable="false"
              :width="100"
              fixed="right"
            >
              <template slot-scope="scope">
                <span
                  v-if="!scope.row.enabled"
                  class="oprate-span"
                  @click="enable(scope.row)"
                  v-functions="['customer_config_field_enable']"
                  >启用</span
                >
                <span
                  v-if="scope.row.enabled && scope.row.category !== 'system'"
                  class="oprate-span red-span"
                  @click="disable(scope.row)"
                  v-functions="['customer_config_field_enable']"
                  >停用</span
                >
                <span
                  class="oprate-span"
                  @click="edit(scope.row, 'edit')"
                  v-functions="['customer_config_field_edit']"
                  >编辑</span
                >
                <span
                  v-if="scope.row.category !== 'system'"
                  class="oprate-span red-span"
                  @click="remove(scope.row)"
                  v-functions="['customer_config_field_delete']"
                  >删除</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <EditFields ref="EditFields" @updateData="updateData"></EditFields>
    </template>
  </continer>
</template>

<script lang="ts">
/**
 * 客户字段
 */
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import { commonAction } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import EditFields from './EditFields.vue'
import { typeArr, getTypeName } from './components/typeMap'
@Component({
  name: 'NoticeSetting',
  components: {
    QuickSearch,
    configTable,
    continer,
    EditFields
  }
})
export default class NoticeSetting extends Vue {
  @Ref() private readonly EditFields: any
  [x: string]: any
  private tableData: any = []
  private pagingData: any = { total: 0, limit: 10, page: 1 }
  private checkHeaders: [] = []
  private quickSearchForm: any = {}

  get AgentList () {
    return (CommonModule as any).publicCache.userList.map(v => ({ name: `${v.agentName} [${v.agentNumber}]`, _id: v._id }))
  }

  private enableData: any = [
    { _id: true, name: '启用' },
    { _id: false, name: '停用' }
  ]

  private optionsData: any = [
    { _id: 'system', name: '系统预置' },
    { _id: 'custom', name: '自定义' }
  ]

  // 获取搜索条目
  private getSelectData () {
    this.quickSearchForm = {
      form: {
        name: '',
        type: [],
        category: '',
        enabled: ''
      },
      advSearchOptions: [
        { label: '字段名称', name: 'name', inputType: 'input', clearable: true, placeholder: '请选择' },
        { label: '字段类型', name: 'type', inputType: 'select', selectData: typeArr(), clearable: true, placeholder: '请选择', multiple: true },
        { label: '字段分类', name: 'category', inputType: 'select', clearable: true, selectData: this.optionsData, placeholder: '请选择' },
        { label: '字段状态', name: 'enabled', inputType: 'select', clearable: true, selectData: this.enableData, placeholder: '请选择' }
      ]
    }
  }

  // 重置
  private reset () {
    this.quickSearchForm.form = {
      name: '',
      type: [],
      category: '',
      enabled: ''
    }
    this.handleSearchFunc()
  }

  private updateData () {
    this.getData()
  }

  private async mounted () {
    this.getSelectData()
    this.getData()
  }

  private getAgentName (agentId) {
    const agent = (CommonModule as any).publicCache.userListObj[agentId]
    if (agent) {
      return agent.name
    }
    return ''
  }

  // 获取数据
  private async getData () {
    const { enabled, name, category, type } = this.quickSearchForm.form
    const actionData: any = {
      limit: this.pagingData.limit,
      page: this.pagingData.page,
      enabled,
      name,
      category: category ? [category] : [],
      type
    }
    const data: any = await commonAction({ url: '/server-crm/action/config/customer/field/list', method: 'POST', data: actionData })
    if (data.success && data.data) {
      this.tableData = data.data.list.map(v => {
        return {
          ...v,
          updateUser: this.getAgentName(v.updateUser),
          filedCategory: v.category === 'custom' ? '自定义' : '系统预置',
          fieldType: getTypeName(v.type)
        }
      })
      this.pagingData.total = data.data.count
    }
  }

  private handleSearchFunc () {
    this.pagingData.page = 1
    this.getData()
  }

  private tableHeaders: object[] = [
    { label: '字段名称', prop: 'name' },
    { label: '字段类型', prop: 'fieldType' },
    { label: '字段参数', prop: 'param' },
    { label: '分类', prop: 'filedCategory' },
    { label: '创建时间', prop: 'createTime' },
    { label: '更新时间', prop: 'updateTime' },
    { label: '更新人', prop: 'updateUser' },
    { label: '状态', prop: 'enabled' },
    { label: '操作', prop: 'oprate', disenable: true }
  ]

  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.getData()
  }

  // 启用
  private enable (item) {
    this.$confirm('请确认是否启用该字段？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const sendData = { enabled: true, field: item.field }
      const res: any = await commonAction({ url: '/server-crm/action/config/customer/field/status', method: 'POST', data: sendData })
      if (res.success) {
        this.$message.success('操作成功')
        this.getData()
      }
    })
  }

  // 禁用
  private disable (item) {
    if (item.category === 'system') {
      return this.$message.error('系统预置的字段不允许停用')
    }
    this.$confirm('停用后，该字段将在系统所有列表中隐藏，包括筛选条件，请确认是否停用？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const sendData = { enabled: false, field: item.field }
      const res: any = await commonAction({ url: '/server-crm/action/config/customer/field/status', method: 'POST', data: sendData })
      if (res.success) {
        this.$message.success('操作成功')
        this.getData()
      }
    })
  }

  // 编辑
  private edit (item, type) {
    this.EditFields.openDraw(item, type)
  }

  // 删除
  private remove (item) {
    this.$confirm('请确认是否删除该字段？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res: any = await commonAction({ url: '/server-crm/action/config/customer/field/delete', method: 'POST', data: { field: item.field } })
      if (res.success) {
        this.$message.success('删除成功')
        this.getData()
        this.$deleteCache('customerAllFields', 'field', item.field, false)
      }
    })
  }
}
</script>
<style lang="stylus" scoped>
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
.red-span, .disable-span
  color $c-danger
  font-size 12px
.enable-span
  color $c-green
  font-size 12px
</style>
